package utile

import (
	"etcd/config"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type Claims struct {
	Uid int `json:"uid"`
	jwt.StandardClaims
}

func CreatToken(uid int) (string, error) {
	conf := config.GetConfig()
	jwtConf := conf.Data.Jwt
	//expire,_ := strconv.ParseInt(jwtConf.Expire, 10, 64)
	claims := Claims{
		Uid: uid,
		StandardClaims: jwt.StandardClaims{
			// 过期时间
			//ExpiresAt: time.Now().Add(time.Second * time.Duration(expire)).Unix(),
			ExpiresAt: time.Now().Add(time.Second * jwtConf.Expire).Unix(),
			// 指定token发行人
			Issuer: "super-admin",
		},
	}
	at := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := at.SignedString([]byte(jwtConf.Secret))
	if err != nil {
		return "", err
	}
	return token, nil
}

func ParseToken(token string) (*Claims, error) {
	conf := config.GetConfig()
	jwtConf := conf.Data.Jwt
	tokenClaim, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(jwtConf.Secret), nil
	})
	if err != nil {
		return nil, err
	}
	res := tokenClaim.Claims.(*Claims)
	return res, nil
}
